//
//  ApIBaseRequest.m
//  APIRequest
//
//  Created by LWW on 2021/10/15.
//  Copyright © 2021 Frank. All rights reserved.
//

#import "APIBaseRequest.h"
#import "DBManager.h"
#import "APIUrlHelper.h"

@implementation APIBaseRequest
- (instancetype)init {
    self = [super init];
    self.method = POST;
    self.isCache = NO;
    return self;
}
- (void)setRequest:(APIBaseRequestHandler *)request{
    _request = request;
}
- (void)apiRequestSuccess:(APISuccessBlock)successBlock
                  failure:(APIFailureBlock)failureBlock{
    
    if (self.request ==nil) {
        NSAssert(NO, @"先获取请求对象");
        return;
    }
    
    NSString *url = self.request.apiRequestURLString;
    NSDictionary *params = self.request.apiRequestParams;
    NSString *cacheKey = [APIUrlHelper connectBaseUrl:url params:params.mutableCopy];
    
    [[NetworkHelper sharedInstance] requestMethod:self.method url:url parameters:params finishBlock:^(id data, NSError *error) {
        if (error) {
            NSDictionary *cacheData = [[DBManager sharedManager] itemWithCacheKey:cacheKey];
            if (!cacheData) {
                self.responseError = error;
                self.responseData = @{};
                failureBlock(error);
                return;
            }
            self.responseData = cacheData;
            successBlock(cacheData);
            return;
        }
        self.responseData = data;
        successBlock(data);
        if (self.isCache) {
             [[DBManager sharedManager] insertItem:data cacheKey:cacheKey];
        }
    }];
}
- (void)apiRequestUploadImagesMethod:(NSArray *)imagesArray urlfileName:(NSString *)urlfileName url:(NSString *)url parameters:(id)parameters finishBlock:(void (^)(id data, NSError *  error))finishBlock{
    [[NetworkHelper sharedInstance] requestUploadImagesMethod:imagesArray urlfileName:urlfileName url:url parameters:parameters finishBlock:^(id data, NSError *error) {
        finishBlock(data,error);
    }];
}
@end
